package com.blog.controller;

import com.blog.common.ServerResponse;
import com.blog.pojo.Article;
import com.blog.pojo.Category;
import com.blog.service.IArticleService;
import com.blog.service.ICategoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author
 * @create 2018-06-04 15:09
 **/
@Controller
@RequestMapping("/article/")
public class ArticleController {

    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private IArticleService articleService;

    @Autowired
    private ICategoryService categoryService;

    /**
     * 查询所有文章
     *
     * @param map
     * @return
     */
    @RequestMapping("list.action")
    public String list(ModelMap map,
                       @RequestParam(required = false, value = "typeId") String typeId,
                       @RequestParam(required = false, value = "startDate") String startDate,
                       @RequestParam(required = false, value = "endDate") String endDate,
                       @RequestParam(required = false, value = "keyWord") String keyWord,
                       @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                       @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("typeId", typeId);
        param.put("startDate", startDate);
        param.put("endDate", endDate);
        param.put("status", "1");
        /*去空格*/
        if (!StringUtils.isEmpty(keyWord)) {
            param.put("keyWord", keyWord.trim());
        }

        // pageHelper分页插件
        // 只需要在查询之前调用，传入当前页码，以及每一页显示多少条
        PageHelper.startPage(pageNum, pageSize);
        //不改变查询
        List<Article> articlesList = articleService.list(param);
        PageInfo<Article> pageInfo = new PageInfo<Article>(articlesList);
        map.put("pageInfo", pageInfo);

        //返回文章分类信息
        List<Category> list = categoryService.list();
        map.put("typeList", list);
        map.put("typeId", typeId);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("keyWord", keyWord);

        return "admin/article/list";
    }

    /**
     * 查询单个文章信息
     *
     * @param id
     * @return
     */
    @RequestMapping("edit.action")
    public String edit(@RequestParam(required = false, value = "id") String id, ModelMap map)  {
        //判断是新增加的还是在原来的文章进行修改的
        if (!StringUtils.isEmpty(id)) {
            Article article = articleService.selectById(id);
            map.put("article", article);
            System.out.println(article.getContent());
        }
        List<Category> list = categoryService.list();
        map.put("typeList", list);

        return "admin/article/edit";
    }


    /**
     * 上传文件到磁盘（物理路径）
     *
     * @throws IOException
     */
    @RequestMapping("upload.json")
    @ResponseBody
    public ServerResponse upload(MultipartFile file, HttpServletRequest request) throws IOException {

        // 文件原名称
        String szFileName = file.getOriginalFilename();
        // 重命名后的文件名称
        String szNewFileName = "";
        // 根据日期自动创建3级目录
        String szDateFolder = "";

        // 上传文件
        if (file != null && szFileName != null && szFileName.length() > 0) {
            Date date = new Date();
            szDateFolder = new SimpleDateFormat("yyyy/MM/dd").format(date);
            // 存储文件的物理路径
            String szFilePath = "E:\\upload\\" + szDateFolder;
            // 自动创建文件夹
            File f = new File(szFilePath);
            if (!f.exists()) {
                f.mkdirs();
            }

            // 新的文件名称
            szNewFileName = UUID.randomUUID() + szFileName.substring(szFileName.lastIndexOf("."));
            // 新文件
            File newFile = new File(szFilePath + "\\" + szNewFileName);

            // 将内存中的数据写入磁盘
            file.transferTo(newFile);
        }
        return ServerResponse.success().add("imgUrl", szDateFolder + "/" + szNewFileName);
    }


    /**
     * 保存单个文章信息
     *
     * @param
     * @return
     */
    @RequestMapping("save.json")
    @ResponseBody
    public ServerResponse save(Article article) {
        return articleService.save(article);
    }


    /**
     * 批量更新分类
     *
     * @param idArr
     * @param typeId
     * @return
     */
    @RequestMapping("updateByType.json")
    @ResponseBody
    public ServerResponse updateByType(@RequestParam(value = "idArr") String[] idArr, @RequestParam(value = "typeId") String typeId) {


        HashMap<String, Object> param = new HashMap();

        param.put("idArr", idArr);
        param.put("typeId", typeId);
        articleService.bachUpdate(param);
        return ServerResponse.success();
    }


    /**
     * 批量删除到回收站
     *
     * @param idArr
     * @return
     */
    @RequestMapping("updateByStatus.json")
    @ResponseBody
    public ServerResponse updateByStatus(@RequestParam(value = "idArr") String[] idArr) {
        HashMap<String, Object> param = new HashMap();
        param.put("idArr", idArr);
        //将状态置为0
        param.put("status", "0");
        articleService.bachUpdate(param);
        return ServerResponse.success();
    }



    @RequestMapping("recycle.action")
    public String recycle(ModelMap map,@RequestParam(required = false, value = "typeId") String typeId,
                          @RequestParam(required = false, value = "startDate") String startDate,
                          @RequestParam(required = false, value = "endDate") String endDate,
                          @RequestParam(required = false, value = "keyWord") String keyWord,
                          @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "3") int pageSize) {

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("typeId", typeId);
        param.put("startDate", startDate);
        param.put("endDate", endDate);
        param.put("status", "0");
        /*去空格*/
        if (!StringUtils.isEmpty(keyWord)) {
            param.put("keyWord", keyWord.trim());
        }

        // pageHelper分页插件
        // 只需要在查询之前调用，传入当前页码，以及每一页显示多少条
        PageHelper.startPage(pageNum, pageSize);
        //不改变查询
        List<Article> articlesList = articleService.list(param);
        PageInfo<Article> pageInfo = new PageInfo<Article>(articlesList);
        map.put("pageInfo", pageInfo);

        //返回文章分类信息
        List<Category> list = categoryService.list();
        map.put("typeList", list);
        map.put("typeId", typeId);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("keyWord", keyWord);
        return "admin/article/list_recycle";
    }

    /**
     * 批量恢复文章
     *
     * @param idArr
     * @return
     */
    @RequestMapping("restore.json")
    @ResponseBody
    public ServerResponse restore(@RequestParam(value = "idArr") String[] idArr) {
        HashMap<String, Object> param = new HashMap();
        param.put("idArr", idArr);
        //将状态置为0
        param.put("status", "1");
        articleService.bachUpdate(param);
        return ServerResponse.success();
    }

    /**
     * 批量删除文章
     *
     * @param idArr
     * @return
     */
    @RequestMapping("delete.json")
    @ResponseBody
    public ServerResponse delete(@RequestParam(value = "idArr") String[] idArr) {
        HashMap<String, Object> param = new HashMap();
        param.put("idArr", idArr);
        articleService.bachDelete(param);
        return ServerResponse.success();
    }
}
